package com.hhw.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//      首页所有人可以访问，但是里面的功能页只有对应有权限的人才能访问
//        请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

//        没有权限，默认跳转回去到登录页
        http.formLogin();

//        注销
//        logoutUrl登录成功时候的注销按钮
//        logoutSuccessUrl登出成功退出的
        http.logout().logoutSuccessUrl("/");
    }

//认证
//        java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"报错密码加密
//        在springsecurity5.0中,新增了很多的加密方式~
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /*这些数据应该从数据库中读取*/
    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
            .withUser("Chaser").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
            .and()
            .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
            .and()
            .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                ;
    }

}
